package com.zyp.demo.service;

import com.zyp.demo.dao.TypesRepository;
import com.zyp.demo.po.Type;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {
@Autowired
private  TypesRepository typesRepository;
    @Transactional/*提交事务*/
    @Override
    public Type saveType(Type type) {
        return typesRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {

        return typesRepository.findById(id).orElse(null);
    }
    @Transactional
    @Override
    public Type getTypeByName(String name) {
        return typesRepository.findByName(name);
    }
    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typesRepository.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typesRepository.findAll();
    }


    @Transactional
    @Override/*更新分类*/
    public Type updateType(Long id, Type type) {
        Type t = typesRepository.findById(id).get();
        if (t == null) {
            try {
                throw new NotFoundException("不存在该类型");
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        }
        BeanUtils.copyProperties(type,t);
        return typesRepository.save(t);
    }
    @Transactional
    @Override
    public void deleteType(Long id) {
        typesRepository.deleteById(id);
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = new PageRequest(0,size,sort );
        return typesRepository.findTop(pageable);
    }
}
